<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="日志级别">
          <el-select
            v-model="filterForm.level"
            placeholder="请选择级别"
            clearable
            class="!w-[120px]"
          >
            <el-option label="DEBUG" value="debug" />
            <el-option label="INFO" value="info" />
            <el-option label="WARN" value="warn" />
            <el-option label="ERROR" value="error" />
            <el-option label="FATAL" value="fatal" />
          </el-select>
        </el-form-item>
        <el-form-item label="日志来源">
          <el-select
            v-model="filterForm.source"
            placeholder="请选择来源"
            clearable
            class="!w-[140px]"
          >
            <el-option label="系统核心" value="system" />
            <el-option label="数据库" value="database" />
            <el-option label="缓存" value="cache" />
            <el-option label="文件系统" value="filesystem" />
            <el-option label="网络" value="network" />
            <el-option label="安全" value="security" />
            <el-option label="定时任务" value="scheduler" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="请输入关键词"
            clearable
            class="!w-[150px]"
          />
        </el-form-item>
        <el-form-item label="记录时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="!w-[350px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline :icon="Search" />
            查询
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline :icon="Refresh" />
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline :icon="Download" />
            导出
          </el-button>
          <el-button type="danger" @click="handleClear">
            <IconifyIconOffline :icon="Delete" />
            清空日志
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <IconifyIconOffline :icon="Document" />
            </div>
            <div class="stat-info">
              <div class="stat-title">总日志数</div>
              <div class="stat-value">{{ systemStats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon info-icon">
              <IconifyIconOffline :icon="InfoFilled" />
            </div>
            <div class="stat-info">
              <div class="stat-title">信息日志</div>
              <div class="stat-value">{{ systemStats.info }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon warn-icon">
              <IconifyIconOffline :icon="Warning" />
            </div>
            <div class="stat-info">
              <div class="stat-title">警告日志</div>
              <div class="stat-value">{{ systemStats.warn }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon error-icon">
              <IconifyIconOffline :icon="CircleCloseFilled" />
            </div>
            <div class="stat-info">
              <div class="stat-title">错误日志</div>
              <div class="stat-value">{{ systemStats.error }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统日志列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统日志列表</span>
          <div>
            <el-button type="info" @click="handleRefresh">
              <IconifyIconOffline :icon="Refresh" />
              刷新
            </el-button>
            <el-button type="warning" @click="handleRealTime">
              <IconifyIconOffline :icon="VideoPlay" />
              {{ isRealTime ? '停止' : '实时' }}监控
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="systemLogList" style="width: 100%" stripe v-loading="loading">
        <el-table-column prop="id" label="日志ID" width="80" />
        <el-table-column prop="level" label="级别" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" size="small">
              {{ row.level.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getSourceTagType(row.source)">
              {{ getSourceText(row.source) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="日志内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="module" label="模块" width="120" show-overflow-tooltip />
        <el-table-column prop="function" label="函数" width="150" show-overflow-tooltip />
        <el-table-column prop="line" label="行号" width="80" align="center" />
        <el-table-column prop="thread" label="线程ID" width="100" />
        <el-table-column prop="timestamp" label="记录时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <IconifyIconOffline :icon="View" />
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="系统日志详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="日志级别">
            <el-tag :type="getLevelTagType(currentLog.level)" size="small">
              {{ currentLog.level.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="日志来源">
            <el-tag size="small" :type="getSourceTagType(currentLog.source)">
              {{ getSourceText(currentLog.source) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模块名称">{{ currentLog.module }}</el-descriptions-item>
          <el-descriptions-item label="函数名称">{{ currentLog.function }}</el-descriptions-item>
          <el-descriptions-item label="代码行号">{{ currentLog.line }}</el-descriptions-item>
          <el-descriptions-item label="线程ID">{{ currentLog.thread }}</el-descriptions-item>
          <el-descriptions-item label="记录时间">{{ formatDateTime(currentLog.timestamp) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 日志内容 -->
        <div class="mt-4">
          <h4>日志内容</h4>
          <el-input
            v-model="currentLog.message"
            type="textarea"
            :rows="4"
            readonly
            class="log-message"
          />
        </div>

        <!-- 堆栈信息 -->
        <div v-if="currentLog.stackTrace" class="mt-4">
          <h4>堆栈信息</h4>
          <el-input
            v-model="currentLog.stackTrace"
            type="textarea"
            :rows="8"
            readonly
            class="stack-trace"
          />
        </div>

        <!-- 上下文信息 -->
        <div v-if="currentLog.context" class="mt-4">
          <h4>上下文信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item
              v-for="(value, key) in currentLog.context"
              :key="key"
              :label="key"
            >
              {{ value }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 相关日志 -->
        <div v-if="currentLog.relatedLogs && currentLog.relatedLogs.length > 0" class="mt-4">
          <h4>相关日志</h4>
          <el-table :data="currentLog.relatedLogs" size="small">
            <el-table-column prop="level" label="级别" width="80">
              <template #default="{ row }">
                <el-tag :type="getLevelTagType(row.level)" size="small">
                  {{ row.level.toUpperCase() }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="内容" show-overflow-tooltip />
            <el-table-column prop="timestamp" label="时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.timestamp) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import Document from "@iconify-icons/ep/document";
import InfoFilled from "@iconify-icons/ep/info-filled";
import Warning from "@iconify-icons/ep/warning";
import CircleCloseFilled from "@iconify-icons/ep/circle-close-filled";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Download from "@iconify-icons/ep/download";
import Delete from "@iconify-icons/ep/delete";
import VideoPlay from "@iconify-icons/ep/video-play";
import View from "@iconify-icons/ep/view";
import dayjs from "dayjs";

defineOptions({
  name: "LogSystem"
});

// 筛选表单
const filterForm = ref({
  level: "",
  source: "",
  keyword: "",
  dateRange: []
});

// 系统统计
const systemStats = ref({
  total: 15432,
  info: 12876,
  warn: 1987,
  error: 569
});

// 系统日志列表
const systemLogList = ref([]);
const loading = ref(false);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 弹窗控制
const detailDialogVisible = ref(false);

// 当前日志记录
const currentLog = ref(null);

// 实时监控
const isRealTime = ref(false);
let realTimeTimer = null;

// 获取级别标签类型
const getLevelTagType = (level: string) => {
  const typeMap = {
    debug: "info",
    info: "success",
    warn: "warning",
    error: "danger",
    fatal: "danger"
  };
  return typeMap[level] || "info";
};

// 获取来源标签类型
const getSourceTagType = (source: string) => {
  const typeMap = {
    system: "primary",
    database: "success",
    cache: "warning",
    filesystem: "info",
    network: "danger",
    security: "danger",
    scheduler: "warning"
  };
  return typeMap[source] || "info";
};

// 获取来源文本
const getSourceText = (source: string) => {
  const sourceMap = {
    system: "系统核心",
    database: "数据库",
    cache: "缓存",
    filesystem: "文件系统",
    network: "网络",
    security: "安全",
    scheduler: "定时任务"
  };
  return sourceMap[source] || source;
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss.SSS");
};

// 生成模拟数据
const generateMockData = () => {
  const mockData = [];
  const levels = ["debug", "info", "warn", "error", "fatal"];
  const sources = ["system", "database", "cache", "filesystem", "network", "security", "scheduler"];
  const modules = ["UserService", "OrderService", "PaymentService", "AuthService", "FileService", "CacheService", "DatabaseService"];
  const functions = ["login", "register", "createOrder", "processPayment", "uploadFile", "queryData", "updateCache"];
  const messages = [
    "用户登录成功",
    "数据库连接建立",
    "缓存更新完成",
    "文件上传失败",
    "网络连接超时",
    "权限验证失败",
    "定时任务执行完成",
    "系统启动完成",
    "内存使用率过高",
    "磁盘空间不足",
    "API调用频率过高",
    "数据库查询超时",
    "Redis连接断开",
    "文件系统错误",
    "SSL证书即将过期"
  ];
  
  for (let i = 1; i <= 100; i++) {
    const level = levels[Math.floor(Math.random() * levels.length)];
    const source = sources[Math.floor(Math.random() * sources.length)];
    const module = modules[Math.floor(Math.random() * modules.length)];
    const func = functions[Math.floor(Math.random() * functions.length)];
    const message = messages[Math.floor(Math.random() * messages.length)];
    const timestamp = dayjs().subtract(Math.floor(Math.random() * 7), 'day')
      .subtract(Math.floor(Math.random() * 24), 'hour')
      .subtract(Math.floor(Math.random() * 60), 'minute')
      .subtract(Math.floor(Math.random() * 60), 'second')
      .subtract(Math.floor(Math.random() * 1000), 'millisecond');
    
    const logData = {
      id: i,
      level,
      source,
      message,
      module,
      function: func,
      line: Math.floor(Math.random() * 1000) + 1,
      thread: `thread-${Math.floor(Math.random() * 10) + 1}`,
      timestamp: timestamp.format('YYYY-MM-DD HH:mm:ss.SSS'),
      context: {
        "用户ID": Math.floor(Math.random() * 10000),
        "会话ID": `session-${Math.random().toString(36).substr(2, 9)}`,
        "请求ID": `req-${Math.random().toString(36).substr(2, 9)}`,
        "IP地址": `192.168.1.${Math.floor(Math.random() * 255)}`
      }
    };
    
    // 为错误级别添加堆栈信息
    if (level === "error" || level === "fatal") {
      logData.stackTrace = `java.lang.Exception: ${message}\n\tat com.example.${module}.${func}(${module}.java:${logData.line})\n\tat com.example.controller.BaseController.handleRequest(BaseController.java:45)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)`;
      
      // 添加相关日志
      logData.relatedLogs = [
        {
          level: "warn",
          message: "检测到异常前置条件",
          timestamp: timestamp.subtract(5, 'second').format('YYYY-MM-DD HH:mm:ss.SSS')
        },
        {
          level: "info",
          message: "开始执行操作",
          timestamp: timestamp.subtract(10, 'second').format('YYYY-MM-DD HH:mm:ss.SSS')
        }
      ];
    }
    
    mockData.push(logData);
  }
  
  return mockData.sort((a, b) => dayjs(b.timestamp).valueOf() - dayjs(a.timestamp).valueOf());
};

// 搜索
const handleSearch = () => {
  loadSystemLogList();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    level: "",
    source: "",
    keyword: "",
    dateRange: []
  };
  loadSystemLogList();
};

// 导出
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm(
      "此操作将永久删除所有系统日志，是否继续？",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    
    ElMessage.success("清空日志功能开发中...");
  } catch {
    ElMessage.info("已取消清空操作");
  }
};

// 刷新
const handleRefresh = () => {
  loadSystemLogList();
};

// 实时监控
const handleRealTime = () => {
  if (isRealTime.value) {
    // 停止实时监控
    isRealTime.value = false;
    if (realTimeTimer) {
      clearInterval(realTimeTimer);
      realTimeTimer = null;
    }
    ElMessage.info("已停止实时监控");
  } else {
    // 开始实时监控
    isRealTime.value = true;
    realTimeTimer = setInterval(() => {
      loadSystemLogList();
    }, 5000); // 每5秒刷新一次
    ElMessage.success("已开启实时监控");
  }
};

// 查看详情
const handleView = (row: any) => {
  currentLog.value = row;
  detailDialogVisible.value = true;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadSystemLogList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadSystemLogList();
};

// 加载系统日志列表
const loadSystemLogList = async () => {
  try {
    loading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const mockData = generateMockData();
    systemLogList.value = mockData.slice(
      (pagination.currentPage - 1) * pagination.pageSize,
      pagination.currentPage * pagination.pageSize
    );
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载系统日志失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadSystemLogList();
});

// 组件卸载
onUnmounted(() => {
  if (realTimeTimer) {
    clearInterval(realTimeTimer);
  }
});
</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.stat-card {
  margin-bottom: 16px;
  
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 20px;
      color: white;
      
      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.info-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.warn-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.error-icon {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  h4 {
    margin: 20px 0 10px 0;
    color: #303133;
    font-weight: bold;
  }
  
  .log-message,
  .stack-trace {
    :deep(.el-textarea__inner) {
      font-family: 'Courier New', monospace;
      font-size: 12px;
      line-height: 1.4;
    }
  }
  
  .stack-trace {
    :deep(.el-textarea__inner) {
      background-color: #f5f5f5;
      color: #e74c3c;
    }
  }
}

@media (max-width: 768px) {
  .main {
    padding: 10px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    
    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }
  
  .pagination-container {
    text-align: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>